<!-- API服务 - 综合表单页面 -->
<template>
  <div class="page-container">
    <ex_super_table_page v-bind="option" ref="SuperTablePage">

    </ex_super_table_page>

    <el-dialog :close-on-click-modal="false" :title="dialogTitle" :visible.sync="dialogVisible" destroy-on-close
      custom-class="dialog_big">
      <div v-loading="dialogLoading" v-loadingCommonStyle>
        <div class="dialog_content">
          <el-form ref="form" :label-width="$globalCss.formLabelWidth_default" :model="dialogForm" :rules="dialogRules">
            <ex_header_spiler :title="$tt('label_base_info')" />
            <el-form-item :label="$tt('label_srm_api_service_platform_type')" prop="platformCode">

              <ex_super_input v-if="this.dialogCreate" v-model="dialogForm.platformCode" type="radio-group" :attrs="{

                items: platList,
                option: { label: e => $formatNameCode(e.platName, e.platCode), value: 'platCode' },
              }" @changeItem="ChangePlat" />
              <span v-else class="bold">{{ $formatNameCode(dialogForm.platformName, dialogForm.platformCode) }}</span>
            </el-form-item>

            <el-form-item :label="$tt('label_srm_api_service_service_type')" prop="apiServiceCode" class="dialog_form_item">

              <!-- <el-radio-group v-model="dialogForm.apiServiceCode">
                <el-radio v-for="(item, i) in platServiceArr" :label="item.serviceCode" :key="i">{{ item.serviceName }}
                  ({{ item.serviceType }})</el-radio>
                        </el-radio-group> -->
              <ex_super_input v-if="this.dialogCreate" v-model="dialogForm.apiServiceCode" type="radio-group" :attrs="{
                items: platServiceList,
                option: { label: e => $formatNameCode(e.serviceName, e.serviceType), value: 'serviceCode' },
              }" @changeItem="ChangePlatformServiceType" />
              <span v-else class="bold">{{ $formatNameCode(dialogForm.apiServiceName, dialogForm.apiServiceCode) }}</span>
            </el-form-item>
            <ex_header_spiler :title="$tt('label_srm_api_service_auth_info')" />

            <!--            <el-form-item label="API服务代码" prop="apiServiceCode">-->
            <!--              <ex_super_input v-if="dialogCreate" v-model="dialogForm.apiServiceCode" class="form_input_default" />-->
            <!--              <span v-else class="bold">{{ dialogForm.apiServiceCode }}</span>-->
            <!--            </el-form-item>-->

            <el-form-item :label="$tt('label_srm_api_service_api_config_name')" prop="apiConfigName" class="dialog_form_item">
              <ex_super_input v-if="dialogCreate" v-model="dialogForm.apiConfigName" class="form_input_default" />
              <span v-else class="bold">{{ dialogForm.apiConfigName }}</span>
            </el-form-item>
            <el-form-item :label="$tt('label_srm_api_service_api_service_auth')" prop="authorize" class="dialog_form_item">
              <ex_super_input v-if="dialogCreate" v-model="dialogForm.authorize" type='select'
                :attrs="{ enum: 'YesOrNoEnum' }" class="form_input_default" />
              <span v-else class="bold">{{ $enumShow(dialogForm.authorize, 'YesOrNoEnum') }}</span>
            </el-form-item>
            <el-form-item :label="$tt('label_srm_api_service_api_service_status')" prop="status" class="dialog_form_item">
              <!-- <ex_super_input  v-model="dialogForm.status" type='select'
                :attrs="{ enum: 'IsAvailableStatusEnum' }" class="form_input_default" /> -->
              <span class="bold">{{ $enumShow(dialogForm.status, 'IsAvailableStatusEnum') }}</span>
            </el-form-item>
            <ex_header_spiler :title="$tt('label_srm_api_service_extras')" />
            <el-skeleton :rows="6" animated :loading="dialogAnnotationLoading">
              <el-form-item v-for="(item, i) in dialogAnnotation" :key="item.key" :label="item.name"
                :class="i ? 'dialog_form_item' : ''">
                <div class="flex_row">
                  <ex_super_input v-model="dialogAnnotationForm[item.key]" @input="changeAnnotationValue"
                    class="form_input_default" />
                  <div class="flex_cell mg_h2">{{ item.explain }}</div>
                </div>
              </el-form-item>
            </el-skeleton>


          </el-form>
        </div>
        <div slot="footer" class="dialog_button_footer mg_t2">
          <el-button type="primary" @click="submitForm" :diabled="dialogSubmiting" :loading="dialogSubmiting">
            {{ $tt('label_submit') }}
          </el-button>
          <el-button @click="dialogVisible = false">{{ $tt('label_fms_account_config_cancel') }}</el-button>
        </div>

      </div>


    </el-dialog>
  </div>
</template>
<script>
let defaultObj = {
  platformName: null,
  platformCode: null,
  apiServiceCode: null,
  apiServiceName: null,//
  apiServiceType: null,// 	LOGISTICS:物流服务商, INSURANCE:保险服务商, CLOUD_WAREHOUSE:云仓服务商
  apiConfigName: null,
  authorize: 'Y',// 	授权：Y=是，N=否

  status: 'ENABLE',// 	E:激活, D:禁用

  parametersAnnotation: null,// 	参数注释说明JSON
  parametersValueDemo: null,// 	参数值示范JSON
  parametersValue: null,// 	参数值JSON
}

import superTablePageFunction from '@/mixin/super-table-page-function';
export default {
  title: 'label_srm_api_service_api_service_info',
  components: {},
  mixins: [superTablePageFunction],
  data() {
    return {

      option: {
        search: {
          model: [
            { label: "label_srm_api_service_config_name", key: "apiConfigName", },
            {
              label: "label_srm_api_service_platform_type", key: "platformCode", type: 'select',
              url: '/srm-api/supplier/ApiServiceRpc/getApiServicePlatformDict.json', storeData: true,
              option: (e)=>({ label: this.$formatNameCode(e.platformName, e.platformCode), value: e['platformCode'] }),
            },
            { label: "label_srm_api_service_service_type", key: "apiServiceType", type: 'select', enum: 'ApiServiceTypeEnum' },
            { label: "label_srm_api_service_service_status", key: "status", type: 'select', enum: 'IsAvailableStatusEnum' },
          ],
        },
        action: [
          {
            label: 'label_srm_api_service_add_api_service',
            auth:'srm_api_service_edit',
            attrs: { icon: "el-icon-plus" }, click: this.clickCreate,
          },
        ],

        table: {
          url: "/srm-api/supplier/ApiServiceRpc/selectList.json",
          model: [
            { key: 'apiConfigName', label: 'label_srm_api_service_config_name', 'min-width': 200, },
            { key: 'platformName', label: 'label_srm_api_service_platform_name', 'min-width': 200, formatter: (r, c, v, i) => this.$formatNameCode(v, r.platformCode) },
            { key: 'apiServiceName', label: 'label_srm_api_service_api_service_name', 'min-width': 200, formatter: (r, c, v, i) => this.$formatNameCode(v, r.apiServiceCode) },
            { key: 'apiServiceType', label: 'label_srm_api_service_api_service_type', 'width': 200, formatter: (r, c, v, i) => this.$enumShow(v, "ApiServiceTypeEnum") },
            { key: 'status', label: 'label_status', 'width': 150, formatter: (r, c, v, i) => this.$enumShow(v, "IsAvailableStatusEnum") },
            {
              type: 'operate', width: 180,
              operate: [
                {
                  label: 'label_srm_api_service_edit_api_service', 
            auth:'srm_api_service_edit',
                  
                  click: this.clickEdit,
                },
                {
                  label: 'label_stop_using', 
            auth:'srm_api_service_disable',
                  
                  type: "confirm-button", url: '/srm-api/supplier/ApiServiceRpc/updateStatus.json', message: '确定要停用该服务吗？',
                  buttonClass: "button_text_danger", confirmButtonType: 'danger',
                  if: (row) => row.status == "ENABLE",
                  params: (row) => { return { "id": row["id"] } }, done: ['reload', 'tip']
                },
                {
                  label: 'IsAvailableStatusEnum__ENABLE', 
            auth:'srm_api_service_disable',
                  
                  type: "confirm-button", url: '/srm-api/supplier/ApiServiceRpc/updateStatus.json', message: '确定要停用该服务吗？',
                  buttonClass: "button_text_success", confirmButtonType: 'success',
                  if: (row) => row.status == "DISABLED",
                  params: (row) => { return { "id": row["id"] } }, done: ['reload', 'tip']
                },
                {
                  label: 'label_delete',
            auth:'srm_api_service_delete',
                  
                  type: "confirm-button", url: '/srm-api/supplier/ApiServiceRpc/remove.json', message: '确定要删除该服务吗？',
                  buttonClass: "button_text_danger", confirmButtonType: 'danger',
                  params: (row) => { return { "id": row["id"] } }, done: ['reload', 'tip']
                },
              ],
            }
          ],

        }
        ,

      },

      dialogTitle: '',
      dialogCreate: false,
      dialogVisible: false,
      dialogLoading: false,
      dialogAnnotationLoading: false,
      dialogSubmiting: false,
      dialogForm: _.cloneDeep(defaultObj),
      dialogAnnotation: [],
      dialogAnnotationForm: {},
      dialogRules: {
        apiConfigName: [{ required: true, message:  this.$tt('tip_can_no_empty'),  trigger: 'blur' }],
        platformCode: [{ required: true, message:  this.$tt('tip_can_no_empty'),  trigger: 'blur' }],
        apiServiceCode: [{ required: true, message:  this.$tt('tip_can_no_empty'), trigger: 'blur' }],
        apiServiceName: [{ required: true, message:  this.$tt('tip_can_no_empty'), trigger: 'blur' }],
        apiServiceType: [{ required: true, message:  this.$tt('tip_can_no_empty'),  trigger: 'blur' }],
        authorize: [{ required: true, message:  this.$tt('tip_can_no_empty'),  trigger: 'blur' }],
        status: [{ required: true, message:  this.$tt('tip_can_no_empty'),  trigger: 'blur' }],
      },



      platList: [],
      platServiceList: [],
    }
  },

  watch: {


  },
  computed: {

  },
  created() {

    this.$ajax({
      url: '/srm-api/supplier/ApiPlatformServiceRpc/getAllPaltforms.json',
      success: (res) => {
        if (res && res.data && res.data.rows) {
          this.platList = res.data.rows
          let headPlatItem = _.head(res.data.rows)
          if (headPlatItem) {
            this.platServiceList = headPlatItem.children;
            defaultObj.platformName = headPlatItem.platName
            defaultObj.platformCode = headPlatItem.platCode
          }


        } else {
          this.$message.error("数据加载失败")
        }
      }
    })


  },

  methods: {
    ChangePlat(e) {
      if (!e) e = { children: [], platName: null, platCode: null }
      this.platServiceList = e.children;
      this.dialogForm.platformName = e.platName
      this.dialogForm.platformCode = e.platCode
      this.resetParameter()
    },
    ChangePlatformServiceType(e) {
      if (!e) e = { serviceCode: null, serviceName: null, serviceTypeCode: null }
      this.dialogForm.apiServiceCode = e.serviceCode
      this.dialogForm.apiServiceName = e.serviceName
      this.dialogForm.apiServiceType = e.serviceTypeCode

      this.refreshParameter()
    },
    refreshParameter() {
      this.resetParameter()
      if (this.dialogForm.platformCode && this.dialogForm.apiServiceType && this.dialogForm.apiServiceCode) {
        this.dialogAnnotationLoading = true
        this.$ajax({
          url: '/srm-api/supplier/ApiServiceRpc/getApiParameters.json',
          method: 'post',
          data: {
            platformCode: this.dialogForm.platformCode,
            apiServiceType: this.dialogForm.apiServiceType,
            apiServiceCode: this.dialogForm.apiServiceCode,
          },
          success: (res) => {
            if (res && res.data) {
              this.dialogForm.parametersAnnotation = res.data.parametersAnnotation
              this.dialogForm.parametersValueDemo = res.data.parametersValueDemo
              this.analyserValue(res.data.parametersValueDemo)
              this.analyserAnnotation(res.data.parametersAnnotation)
            } else {
              this.$message.error("数据解析失败")
            }
          },
          complete: () => {
            this.dialogAnnotationLoading = false
          }
        })
      }
    },
    resetParameter() {
      this.dialogForm.parametersAnnotation = null
      this.dialogForm.parametersValueDemo = null
      this.dialogForm.parametersValue = null
      this.dialogAnnotation = []
      this.dialogAnnotationForm = {}
    },
    changeAnnotationValue() {
      try {
        this.dialogForm.parametersValue = JSON.stringify(this.dialogAnnotationForm)
      } catch (e) {
        this.dialogForm.parametersValue = null
        this.$message.error("数据解析失败")
      }

    },
    clickCreate() {
      this.dialogTitle = '新增API服务'

      this.dialogCreate = true
      this.dialogVisible = true
      this.dialogForm = _.cloneDeep(defaultObj)

      this.ChangePlat(null)
      if (this.$refs['form']) this.$refs['form'].clearValidate()
    },

    analyserValue(json) {
      try {
        this.dialogAnnotationForm = JSON.parse(json)
      } catch (e) {
        this.dialogAnnotationForm = {}
        this.$message.error("数据解析失败")
      }


    },
    analyserAnnotation(json) {
      try {
        let parametersAnnotation = JSON.parse(json)
        let listAnnotation = []
        _.forOwn(parametersAnnotation, (value, key) => {
          listAnnotation.push({
            key,
            ...value
          })
        })
        this.dialogAnnotation = listAnnotation.sort((a, b) => a.index - b.index)
      } catch (e) {
        this.$message.error("数据解析失败")
        this.dialogAnnotation = []
      }
    },

    clickEdit(row) {
      this.dialogTitle = '编辑API服务'

      this.dialogCreate = false
      this.dialogVisible = true
      this.dialogLoading = true
      this.resetParameter()
      this.$ajax({
        url: '/srm-api/supplier/ApiServiceRpc/detail.json',
        method: 'post',
        data: { id: row.id },
        success: (res) => {

          if (res && res.data) {
            this.dialogForm = Object.assign({}, _.cloneDeep(defaultObj), res.data)
            this.analyserValue(res.data.parametersValue)
            this.analyserAnnotation(res.data.parametersAnnotation)
          } else {
            this.$message.error("数据解析失败")
          }

        },
        complete: () => {
          this.dialogLoading = false
        }
      })
    },
    submitForm() {

      this.$refs['form'].validate((valid) => {
        if (valid) {

          this.dialogSubmiting = true
          this.$ajax({
            url: this.dialogCreate ? '/srm-api/supplier/ApiServiceRpc/saveUpdate.json' : '/srm-api/supplier/ApiServiceRpc/update.json',
            method: 'post',
            type: 'json',
            loading: "提交中",
            data: this.dialogForm,
            success: (res) => {
              this.dialogVisible = false
              this.$message.success(this.$tt("tip_submit_success"))
              this.reload()
            },
            complete: () => {
              this.dialogSubmiting = false
            }
          })
        } else {
          this.$message.error(this.$tt('form_validate_error'))
          return false;
        }
      });
    },
  }
};

</script>
<style>
.dialog_big .dialog_content {
  height: 60vh;
  padding: 0.5rem;
  border: 2px solid #eee;
  border-radius: 5px;
  overflow: auto;
}

.dialog_content .dialog_form_item {
  border-top: 1px dashed #dcdfe6;
  padding-top: 1rem;
}
</style>
